from data_set import DataSet
from csv import excel as excel_dialect
from csv import writer as csv_writer
from csv import reader as csv_reader
import csv
from csv import QUOTE_ALL
import io

csv_dialect = excel_dialect
csv_dialect.lineterminator = '\n'
csv_dialect.delimiter = ';'
csv_dialect.quoting = QUOTE_ALL

def unicode_csv_reader(unicode_csv_data, dialect=csv_dialect, **kwargs):
    # csv.py doesn't do Unicode; encode temporarily as UTF-8:
    csv_reader = csv.reader(utf_8_encoder(unicode_csv_data),
                            dialect=dialect, **kwargs)
    for row in csv_reader:
        # decode UTF-8 back to Unicode, cell by cell:
        yield [unicode(cell, 'utf-8') for cell in row]

def utf_8_encoder(unicode_csv_data):
    for line in unicode_csv_data:
        yield line.encode('utf-8')

class CSV(DataSet):
    '''
    Superseeds data_set.DataSet with methods for reading / writing from / to CSV files
    '''


    csv_dialect = excel_dialect
    csv_dialect.lineterminator = '\n'
    csv_dialect.delimiter = ';'
    csv_dialect.quoting = QUOTE_ALL

    def __init__(self, target_file):
        '''
        Superseeds data_set.DataSet with methods for reading / writing from / to CSV files

        :param target_file: CSV file to read or write
        '''
        DataSet.__init__(self)
        self.target_file = target_file

    def get_target_file(self):
        return self.__target_file

    def set_target_file(self, value):
        self.__target_file = value

    def del_target_file(self):
        del self.__target_file


    def read(self):
        with io.open(self.target_file, mode='r', encoding='cp1252') as csvFile:
            reader = unicode_csv_reader(csvFile, dialect=self.csv_dialect)
            for row in reader:
                self.l.append(row)
        return self

    def write(self):
        with open(self.target_file, 'w') as csvFile:
            writer = csv_writer(csvFile, dialect=self.csv_dialect)
            for row in self.l:
                    writer.writerow(row)
        return self

    target_file = property(get_target_file, set_target_file, del_target_file, "CSV file to read or write")
